import { reactive, createApp, createVNode } from 'vue';
import { Messages } from './Message.js';
import usePortal from '../use/usePortal.js';
import { createUniqueId } from '../use/createUniqueId.js';

function Message() {
  const store = reactive({
    list: []
  });
  const ele = usePortal('cm-message-portal', 'cm-messages-wrap');
  const onClose = item => {
    const items = store.list.filter(aitem => {
      return aitem.key !== item.key;
    });
    store.list = [...items];
  };
  createApp(() => createVNode(Messages, {
    "data": store.list,
    "onClose": onClose
  }, null)).mount(ele);
  return {
    close: key => {
      const item = store.list.find(aitem => {
        return aitem.key === key;
      });
      onClose(item);
      if (item) {
        item.onClose && item.onClose();
      }
    },
    open: (config, type) => {
      if (typeof config === 'string') {
        config = {
          content: config
        };
      }
      if (!config.key) {
        config.key = createUniqueId();
      }
      config.type = type;
      store.list.push(config);
    },
    info(config) {
      this.open(config, 'info');
    },
    success(config) {
      this.open(config, 'success');
    },
    warning(config) {
      this.open(config, 'warning');
    },
    error(config) {
      this.open(config, 'error');
    }
  };
}
const message = Message();

export { message };
